package com.diy.sigmund.diycommon.util;

import com.google.common.collect.Lists;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Optional;
import java.util.function.Function;

/**
 * 批处理程序
 *
 * @author ylm-sigmund
 * @since 2020/10/11 20:31
 */
public class BatchProgramUtil {

    public static final int DEFAULT_SIZE = 100;

    public static final int BIGGER_SIZE = 300;

    /**
     * 不需要声明接口，直接使用Function
     */
    public static <T> int apply(List<T> list, int batchSize, Function<List<T>, Integer> function) {
        if (CollectionUtils.isEmpty(list)) {
            return 0;
        }
        int resultNum = 0;
        List<List<T>> partition = Lists.partition(list, batchSize);
        for (List<T> subList : partition) {
            resultNum += Optional.ofNullable(function.apply(subList)).orElse(0);
        }
        return resultNum;
    }
}